import 'package:flutter/material.dart';
import 'package:flutter_ncsjqz_getx/constant/constant.dart';
import 'package:flutter_ncsjqz_getx/http/dio_service.dart';
import 'package:flutter_ncsjqz_getx/model/base_entity.dart';
import 'package:flutter_ncsjqz_getx/page/home/home_view.dart';
import 'package:flutter_ncsjqz_getx/page/my/userinfo_setting/user_info_setting_logic.dart';
import 'package:flutter_ncsjqz_getx/util/regexp_util.dart';
import 'package:flutter_ncsjqz_getx/util/toast_util.dart';
import 'package:flutter_ncsjqz_getx/widget/app_bar_widget.dart';
import 'package:flutter_ncsjqz_getx/widget/gradient_button.dart';
import 'package:flutter_ncsjqz_getx/widget/ink_widget.dart';
import 'package:flutter_ncsjqz_getx/widget/input_widget.dart';
import 'package:get/get.dart';

import 'email_password_logic.dart';

/// <summary>
/// todo: 绑定邮箱、绑定手机号、绑定密码
/// author：zwb
/// dateTime： 2021/11/8 13:46
/// filePath： lib/page/my/history_relese/history_release_view.dart
/// desc:
/// <summary>
///
enum EPW {
  phone,
  email,
  pwd,
  getPwd,
}

class EmailPhonePasswordPage extends StatefulWidget {
  final String? title; // 标题
  final EPW? type; // 页面类型
  final String emailPhone; // 邮箱号 / 手机号
  final bool? qz; // 是否強制設置手機號

  EmailPhonePasswordPage({
    this.title,
    this.type: EPW.email,
    this.emailPhone: "", this.qz:false,
  });

  @override
  _EmailPhonePasswordPageState createState() => _EmailPhonePasswordPageState();
}

class _EmailPhonePasswordPageState extends State<EmailPhonePasswordPage> {
  final logic = Get.put(EmailPasswordLogic());

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    logic.type = widget.type;
  }
  @override
  Widget build(BuildContext context) {
    widget.type == EPW.email ? logic.textEditingControllerEmail.text = widget.emailPhone : logic.textEditingControllerTel.text = widget.emailPhone ;
    return Scaffold(
      resizeToAvoidBottomInset: false,
      appBar: appBarWidget(title: widget.title ?? '',leading: widget.qz == true ? SizedBox():null),
      body: GetBuilder<EmailPasswordLogic>(
        builder: (controller) {
          return Padding(
            padding: EdgeInsets.all(15),
            child: Column(
              children: [
                !logic.setNewPassword
                  ? SizedBox(
                      width: Get.width,
                      height: 50,
                      child: textFieldWidget(
                        enabled: widget.type == EPW.pwd ? false : true, // 修改密码  不让更改电话号码
                        controller: widget.type == EPW.email ? logic.textEditingControllerEmail : logic.textEditingControllerTel,
                        circular: 0,
                        maxLength: widget.type == EPW.email ? 50 : 11,
                        maxLines: 1,
                        keyboardType: widget.type == EPW.email ? TextInputType.emailAddress : TextInputType.phone,
                        hintText: widget.type == EPW.email ? "请输入绑定的邮箱" : "请输入您的手机号",
                        prefixIcon: InkWidget.imgAsset("my_select.png", padding: EdgeInsets.all(15),),
                      ),
                    )
                  : SizedBox(
                      width: Get.width,
                      height: 50,
                      child: textFieldWidget(
                        controller: logic.textEditingControllerPwd,
                        circular: 0,
                        obscureText: true,
                        maxLines: 1,
                        hintText: "请输入新密码",
                        prefixIcon: InkWidget.imgAsset("my_select.png", padding: EdgeInsets.all(15),),
                      ),
                    ),
                SizedBox(
                  height: 20,
                ),
                Offstage(
                  offstage: widget.type == EPW.email,
                  child: !logic.setNewPassword
                      ? SizedBox(
                    width: Get.width,
                    height: 50,
                    child: textFieldWidget(
                      controller: logic.textEditingControllerCode,
                      circular: 0,
                      hintText: "请输入验证码",
                      maxLines: 1,
                      maxLength: 6,
                      keyboardType: TextInputType.phone,
                      prefixIcon: InkWidget.imgAsset("code.png",
                          padding: EdgeInsets.all(15)),
                      suffixIcon: logic.setTimeLent == logic.getTimeDown
                          ? SizedBox(
                        child: gradientButton("发送验证码", onTap: ()async {
                          if (widget.title == "绑定邮箱") {
                            if (logic.textEditingControllerEmail.value.text =="") return toast("邮箱号未输入");
                            await logic.getEmail();
                          } else {
                            if (logic.textEditingControllerTel.value.text =="") return toast("手机号未输入");
                            if (!RegExps.phoneExp.hasMatch(logic.textEditingControllerTel.value.text)) return toast("手机号格式有误");
                            await logic.getSms();
                          }
                        }),
                      )
                          : OutlineButton(
                        onPressed: () {},
                        child: Text("${logic.getTimeDown}"),
                        borderSide: BorderSide(color: Colors.green),
                      ),
                    ),
                  )
                      : SizedBox(
                    width: Get.width,
                    height: 50,
                    child: textFieldWidget(
                      controller: logic.textEditingControllerPwd1,
                      circular: 0,
                      obscureText: true,
                      maxLines: 1,
                      hintText: "再次确认新密码",
                      prefixIcon: InkWidget.imgAsset("my_select.png",
                          padding: EdgeInsets.all(15)),
                    ),
                  ),
                ),
                Offstage(
                  offstage: widget.type == EPW.email,
                  child: SizedBox(
                    height: Get.width / 2,
                  ),
                ),
                _bottomButton(),
              ],
            ),
          );
        },
      ),
    );
  }

  _bottomButton() {
    String btnName = "";
    if (widget.type == EPW.email) {
      btnName = "确定并提交";
    } else if (!logic.setNewPassword) {
      btnName = "下一步";
    } else {
      btnName = "确定修改";
    }
    return ClipRRect(
      borderRadius: BorderRadius.circular(40),
      child: SizedBox(
        width: Get.width * 0.7,
        child: gradientButton(btnName, onTap: () async {
          /// 校验邮箱非空
          if (widget.type == EPW.email && logic.textEditingControllerEmail.value.text == "") return toast("邮箱未输入");
          /// 校验验证码非空
          if (logic.textEditingControllerCode.value.text == "" && widget.type != EPW.email) return toast("验证码未输入");
          /// 通过校验结束验证码计时器
          logic.endTimeDown();
          if (widget.type == EPW.pwd) {  // 修改密码
            /// 校验2次密码
            if(logic.setNewPassword && logic.textEditingControllerPwd.value.text!=logic.textEditingControllerPwd1.value.text) return toast("两次密码不一致");
            /// 设置新密码
            if(logic.setNewPassword){
              Map<String,dynamic> map = {
                "id": Constant.userDetailData!.id,
                "passWord":logic.textEditingControllerPwd.value.text};
              Get.put(UserInfoSettingLogic()).setUserInfo(map).then((value){
                if(value.code == 0){
                  toast("新密码设置成功");
                  Get.back();
                }
              });
              return;
            }
            /// 切换到修改密码面板
            logic.setNewPwd();
          } else if(widget.type == EPW.phone){// 修改手机号
            Map<String,dynamic> map = {
              "id": Constant.userDetailData!.id,
              "telPhone":logic.textEditingControllerTel.value.text,
              "smsCode": logic.textEditingControllerCode.value.text,
            };
            Get.put(UserInfoSettingLogic()).setUserInfo(map).then((value){
              if(value.code == 0){
                toast("手机号设置成功");
                if(widget.qz == true){
                  Get.off(()=>HomePage());
                }else{
                  Get.back();
                }
              }
            });
          }else if(widget.type == EPW.getPwd){
            /// 切换到修改密码面板
            logic.setNewPwd();
            if(logic.textEditingControllerPwd.text == "") return;
            if(logic.setNewPassword && logic.textEditingControllerPwd.value.text!=logic.textEditingControllerPwd1.value.text) return toast("两次密码不一致");
            Map<String,dynamic> map = {
              "accountType": 0,
              "newPassword": logic.textEditingControllerPwd1.text,
              "passWord": logic.textEditingControllerPwd.text,
              "smsCode": logic.textEditingControllerCode.text,
              "telPhone": logic.textEditingControllerTel.text
            };
            BaseEntity data = await DioService<BaseEntity>().retrievePwd(map);
            if(data.code == 0){
              toast("已找回");
              Get.back();
            }
          }else{
            logic.setEmail();
          }
        }),
      ),
    );
  }

  @override
  void dispose() {
    Get.delete<EmailPasswordLogic>();
    super.dispose();
  }
}
